import Metadata from 'next';
import { getAuthors } from '@/models';
import { gfetch } from '@/utils/back/fetch';
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';

export async function getCategoryList(request: NextRequest) {
  const { searchParams } = request.nextUrl;

  const data = await gfetch<Obj>(
    `${process.env.NEXT_PUBLIC_DSZ_API_DOMAIN}/v2/categories?${searchParams.toString()}`
  );
  return NextResponse.json(data);
}

export function catalogSearchDataCallback(data: string) {
  const liList = data.match(/<li[^>]*>(.*?)<\/li>/g) ?? [];
  const parse = (liHtml: string) => {
    const spanList = liHtml.match(/<span[^>]*>(.*?)<\/span>/g);
    const spanHtml = spanList?.[0] ?? '';
    const relatedKW = liHtml
      .replace(spanHtml, '')
      .replace(/<li[^>]*>|<\/li>/g, '')
      .trim();
    const spanMatched = liHtml.match(/<span[^>]*>(.*?)<\/span>/);
    const count = Number(spanMatched?.[1] ?? 0);

    if (!relatedKW || !count) return false;

    return { relatedKW, count };
  };

  const result = liList.map(parse).filter(item => !!item);
  return result;
}
